package ants_v2

import (
	"fmt"
	"sync"
)

type workerState string

const (
	running     workerState = "Running"
	idle        workerState = "Idle"
	blocked     workerState = "Blocked"
	timeWaiting workerState = "TimeWaiting"
)

type Pool struct {
	Capacity int
	workers  []*Worker
	running  int

	lock sync.Locker
}

// Submit job to the pool
// if there is no more worker to do the job
// then push the job to the queue
func (p *Pool) Submit(task func()) {
	p.getWorker().taskChan <- task
}

// get available worker from the pool
func (p *Pool) getWorker() *Worker {
	if p.isFull() {
		panic("pool is full and reject")
	}

	w := p.createWorker()
	p.workers = append(p.workers, w)
	return w
}

func (p *Pool) createWorker() *Worker {
	w := &Worker{
		taskChan: make(chan func()),
		pool:     p,
	}
	w.run()
	p.lock.Lock()
	p.running += 1
	p.lock.Unlock()
	fmt.Printf("running workers #%d\n", p.running)

	return w
}

// Returns true if running workers greater than capacity
func (p *Pool) isFull() bool {
	return p.running >= p.Capacity
}
